package org.eden.karb.activity.impl;

import org.eden.karb.activity.EventAnalyser;
import org.eden.karb.configuration.Configuration;
import org.eden.karb.configuration.ConfigurationService;
import org.eden.karb.event.EventDispatcher;
import org.eden.karb.event.impl.AudioMonitorEvent;
import org.eden.karb.event.impl.AudioStartRecordEvent;
import org.eden.karb.session.SessionManager;
import org.eden.karb.session.entity.ActiveSession;
import org.jthompson.monsoon.annotations.Event;

import javax.annotation.Resource;

/**
 * @author trsimoes
 */
public class AudioEventAnalyserImpl implements EventAnalyser<AudioMonitorEvent>, EventDispatcher<AudioStartRecordEvent,
        AudioStartRecordEvent.AudioStartRecordEventParameters> {

    @Resource
    private ConfigurationService configurationService;

    @Resource
    private SessionManager sessionManager;

    public void process(AudioMonitorEvent event) {

        int recordingLevel = configurationService.get(Configuration.RECORDING_INPUT_LEVEL, Integer.class);
        int numberOfUnacceptableHits = configurationService.get(Configuration.RECORDING_NUMBER_OF_HITS_PER_SAMPLE,
                Integer.class);

        int[] levels = event.getLevels();
        boolean unusualActivity = false;
        int hitCounter = 0;

        for (int level : levels) {
            if (level >= recordingLevel) {
                hitCounter++;
            }
            if (hitCounter == numberOfUnacceptableHits) {
                unusualActivity = true;
                break;
            }
        }

        if (unusualActivity) {

            ActiveSession activeSession = sessionManager.getSession(event.getSessionId());
            if (activeSession.isRecording()) {
                // update recordStartTime
            } else {
                AudioStartRecordEvent.AudioStartRecordEventParameters parameters = new AudioStartRecordEvent
                        .AudioStartRecordEventParameters();
                parameters.setSessionId(event.getSessionId());
                publish(parameters);
            }
        }
    }

    @Event(name = "audioRecord", type = Event.EventType.DISPATCHER)
    public AudioStartRecordEvent publish(AudioStartRecordEvent.AudioStartRecordEventParameters parameters) {
        return new AudioStartRecordEvent(parameters.getSessionId());
    }
}
